package com.mikelouis.test.scala.proginscala.chapter28

/**
 * This Point's equality method depends on mutable variables, and
 * so its results are not stable when the variables change.
 * Created by yuazhu on 2/26/2015.
 */
object Points4 {

  class Point(var x: Int, var y: Int) {
    // Problematic
    override def hashCode = 41 * (41 + x) + y

    override def equals(other: Any) = other match {
      case that: Point => this.x == that.x && this.y == that.y
      case _ => false
    }
  }

  def main(args: Array[String]) {
    val p = new Point(1, 2)
    val col1 = scala.collection.mutable.HashSet(p)
    println(col1 contains p)

    // hashCode or equals method is not stable
    p.x +=1
    // after change, the hashCode has changed, so contains method can't access the new hashCode element
    println(col1 contains p)
    // while the iterator contains element p
    println(col1.iterator contains p)
  }
}
